package kr.hkit.androidcomplete02.ch16;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.ListFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class RadioQuestionFrg extends Activity implements ListDialogFragment.NoticeDialogListener{
	TextView tv;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch16_dialogtest);
		tv = (TextView) findViewById(R.id.p_text);
		
	}
	
	public void mOnClick(View v){
		ListDialogFragment listFrg = new ListDialogFragment();
		listFrg.show(getFragmentManager(), "dialog");
	}

	@Override
	public void onDialogClick(DialogFragment frg, String res) {
		tv.setText("선택한 과일은 : " + res);
	}
	
	
}

class ListDialogFragment extends DialogFragment{
	NoticeDialogListener mListener;
	int mSelect;
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		
		try{
		mListener = (NoticeDialogListener) activity;
		}catch(ClassCastException e){
			Log.d("ClassCastException", activity.toString() + "ListDialogFragment을 구현");
		}
		
	}
	// OnDialogClick()를 인터페이스로 정의!
	public interface NoticeDialogListener{
		public void onDialogClick(DialogFragment frg, String res);
	}
	
	//.setSingleChoiceItems() : 라디오 버튼 추가
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		return new AlertDialog.Builder(getActivity())
		.setTitle("음식을 선택하시오")
		.setIcon(R.drawable.ic_launcher)
		.setSingleChoiceItems(R.array.fruits, mSelect, new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				mSelect = which;
			}
		})
		/*.setItems(R.array.fruits, new OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				String[] fruits = getResources().getStringArray(R.array.fruits);
				mListener.onDialogClick(ListDialogFragment.this, fruits[which]);
			}
		})*/
		.setPositiveButton("확인", new OnClickListener() {
			// onClick()에서 which는 누르는 버튼의 id값
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(getActivity(), "which : " + which + " mSelect : " + mSelect, Toast.LENGTH_SHORT).show();
				
				String[] fruits = getResources().getStringArray(R.array.fruits);
				mListener.onDialogClick(ListDialogFragment.this, fruits[mSelect]);
			}
		})
		.setNegativeButton("취소", null)
		.create();
	}
}
